package com.sy.service.impl;

import com.alibaba.excel.EasyExcel;
import com.sy.bean.*;
import com.sy.bean.excel.EnterpriseData;
import com.sy.common.crud.BaseServiceImpl;
import com.sy.common.exception.BusinessException;
import com.sy.mapper.AccountDetailMapper;
import com.sy.mapper.EnterpriseCategoryMapper;
import com.sy.mapper.EnterpriseMapper;
import com.sy.service.EnterpriseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Map;

@Service
public class EnterpriseServiceImpl extends BaseServiceImpl<Enterprise, EnterpriseMapper> implements EnterpriseService {
    @Autowired
    AccountDetailMapper accountDetailMapper;
    @Autowired
    EnterpriseCategoryMapper enterpriseCategoryMapper;
    @Autowired
    HttpServletRequest request;
    @Autowired
    EnterpriseMapper enterpriseMapper;
    private String currentMaxCode;//当前最大编码

    @Transactional
    @Override
    public int save(Enterprise entity) {
        //查询是否存在
        int count = baseMapper.existName(entity.getName());
        if (count > 0)
            throw new BusinessException("企业名称已存在");
        //可以用时，生成编码
        String code = generateNewCode();
        entity.setCode(code);
        int rs = super.save(entity);
        if (rs == 0)
            throw new BusinessException("保存企业失败");
        //更新类目数量
        rs = enterpriseCategoryMapper.addEnterpriseNum(entity.getCategoryCode());
        if (rs==0){
            throw new BusinessException("该编号不存在");
        }
        return rs;
    }

    @Override
    public int auth(Permissions permissions) {
        return baseMapper.auth(permissions);
    }

    @Transactional
    @Override
    public int renewal(Renewal renewal) {
        //更新企业余额及时间
        int rs = baseMapper.renewal(renewal);
        if (rs == 0)
            throw new BusinessException("更新企业余额失败");
        if (renewal.getMonth()>0){
            //如果有增加会员日期，判断是否为首次，如果是 更新开通日期
            baseMapper.updateBeginDate(renewal.getEid());
        }
        //更新成功 添加账户变动明细
        AccountDetail detail = new AccountDetail();
        detail.setType(2);
        detail.setEid(renewal.getEid());
        detail.setReason("企业续费" + renewal.getMonth() + "个月");
        detail.setMoney(renewal.getMoney());
        rs = accountDetailMapper.save(detail);
        return rs;
    }

    @Override
    public Map queryMapper(Map map) {
        return baseMapper.queryMoney(map);
    }

    String generateNewCode() {
        //如果编码存在
        if (null != currentMaxCode) {
            return getNxtCode(currentMaxCode);
        }
        //内存中没有，去数据库查询最大编码
        currentMaxCode = baseMapper.queryMaxCode();
        if (null == currentMaxCode) {
            //当前没有编码 赋初始值
            currentMaxCode = "1000001";
            return currentMaxCode;
        }
        //如果存在
        return getNxtCode(currentMaxCode);
    }

    String getNxtCode(String currentCode) {
        //如果内存中存在最大编码
        //转换编码为数字
        int tmp = Integer.parseInt(currentCode);
        //编码+1
        tmp++;
        //记录最新编码
        currentMaxCode = String.valueOf(tmp);
        return currentMaxCode;
    }

    @Override
    public String export(Map map) {
        List<EnterpriseData> list = baseMapper.export(map);
        String root = request.getServletContext().getRealPath("/")+"/excel";
        File file = new File(root);
        if (!file.exists())
            file.mkdirs();
        String newFileName = file.getAbsolutePath()+"/企业列表.xlsx";
        EasyExcel.write(newFileName,EnterpriseData.class)
                .sheet("企业列表")
                .doWrite(()->{
                    return list;
                });
        return "/excel/企业列表.xlsx";
    }

    @Override
    public RenewalAll queryRenById(Map map) {
        return enterpriseMapper.queryRenById(map);
    }

    @Override
    public Map queryByUserId(int id) {
        return enterpriseMapper.queryByUserId(id);
    }
}
